package com.nariano.server.utils.spring;

import org.springframework.beans.factory.BeanFactoryUtils;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public abstract class SpringFactory {
    /**
     * Spring XML config file locations.
     */
    public static final String DEFAULT_BEAN_CONFIGS[] = new String[] { "/nariano-beans.xml" };

    private static ConfigurableApplicationContext beanFactory;

    /**
     * Lookup a Spring managed bean by name.
     * 
     * @param name
     *            the bean name
     * @return an instance (singleton or prototype) of the given type
     */
    public static Object getBean(String name) {
        return getBean(name, Object.class);
    }

    /**
     * Lookup a Spring managed bean by name and type.
     * 
     * @param name
     *            the bean name
     * @param type
     *            the bean type
     * @return an instance (singleton or prototype) of the given type
     */
    public static <T> T getBean(String name, Class<T> type) {
        return (T) beanFactory.getBean(name, type);
    }

    /**
     * Lookup a Spring managed bean by type.
     * 
     * @param type
     *            the bean type
     * @return an instance (singleton or prototype) of the given type
     */
    public static <T> T getBean(Class<T> type) {
        return (T) BeanFactoryUtils.beanOfType(beanFactory, type);
    }
    
    public static void start(String[] serviceResources) {
    	synchronized (DEFAULT_BEAN_CONFIGS) {
    		if (beanFactory==null) {
        		beanFactory =  new ClassPathXmlApplicationContext(serviceResources);
        	}
		}
    	// Just touch the beanFactory, so it gets loaded
        beanFactory.getBeanFactory();
	}

    public static void start() {
    	
        start(DEFAULT_BEAN_CONFIGS);
    }

    public static void stop() {
        beanFactory.close();
    }

	
}
